//
//  WelcomViewController.swift
//  Weibo8023
//
//  Created by styshy on 15/12/10.
//  Copyright © 2015年 sz. All rights reserved.
//

import UIKit
import SDWebImage

class WelcomViewController: UIViewController {
    
/// 设置界面，视图的层次结构
    override func loadView() {
        view = backImageView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
         setupUI()
        
        // 异步加载网络头像
        iconView.sd_setImageWithURL(UserAccountViewModel.sharedUserAccount.avatarUrl, placeholderImage: UIImage(named: "avatar_default_big"))
        
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidDisappear(animated)
        
        iconView.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(-view.bounds.height + 200)
        }
        
        // 2. 动画
        welcomeLabel.alpha = 0
        UIView.animateWithDuration(1.2, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 10, options: [], animations: { () -> Void in
            
            // 修改所有`可动画`属性 - 自动布局的动画
            self.view.layoutIfNeeded()
            
            }) { (_) -> Void in
                
                UIView.animateWithDuration(0.8, animations: { () -> Void in
                    self.welcomeLabel.alpha = 1
                    }, completion: { (_) -> Void in
                        
                        print("OK")
                        // 不推荐的写法
                        // UIApplication.sharedApplication().keyWindow?.rootViewController = MainViewController()
                        // 发送通知
                        NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootViewControllerNotification, object: nil)
                })
        }

    }


    // MARK: - 懒加载控件
    // 1.背景图片
    private lazy var backImageView:UIImageView = UIImageView(imageName: "ad_background")
    
    // 2.头像
    private lazy var iconView:UIImageView = {
        let iv = UIImageView(imageName: "avatar_default_big")
        
        iv.layer.cornerRadius = 45
        iv.layer.masksToBounds = true

        return iv
    }()
    
    // 设置欢迎标签
    private lazy var welcomeLabel:UILabel = UILabel(title: "欢迎归来", fontSize: 18)
    
}

// MARK:- 设置用户界面
extension WelcomViewController{
    private func setupUI(){
        view.addSubview(iconView)
        view.addSubview(welcomeLabel)
        
        
        iconView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(view.snp_centerX)
            make.bottom.equalTo(view.snp_bottom).offset(-200)
            make.width.equalTo(90)
            make.height.equalTo(90)
        }
        welcomeLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(iconView.snp_centerX)
            make.top.equalTo(iconView.snp_bottom).offset(16)
        }
    }
}
